using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using CCWin.SkinControl;

namespace ERPWinFormWork.Material
{
    public partial class WorkOrderSelectForm : Skin_Mac
    {
        private ApiClient _apiClient;
        private DataTable _workOrderData;
        private string _selectedWorkOrderName;
        private string _selectedWorkOrderNumber;

        public string SelectedWorkOrderName => _selectedWorkOrderName;
        public string SelectedWorkOrderNumber => _selectedWorkOrderNumber;

        public WorkOrderSelectForm()
        {
            InitializeComponent();
            _apiClient = new ApiClient("http://localhost:5280/api/");
            InitializeDataGridView();
            LoadWorkOrderData();
        }

        private void InitializeDataGridView()
        {
            // 设置DataGridView的基本属性
            dgvWorkOrders.AllowUserToAddRows = false;
            dgvWorkOrders.AllowUserToDeleteRows = false;
            dgvWorkOrders.ReadOnly = false;
            dgvWorkOrders.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvWorkOrders.MultiSelect = false;
            dgvWorkOrders.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            // 添加复选框列
            var checkBoxColumn = new DataGridViewCheckBoxColumn
            {
                Name = "colSelect",
                HeaderText = "选择",
                Width = 60,
                ReadOnly = false
            };
            dgvWorkOrders.Columns.Add(checkBoxColumn);

            // 添加其他列
            dgvWorkOrders.Columns.Add("colWorkOrderNumber", "工单编号");
            dgvWorkOrders.Columns.Add("colWorkOrderName", "工单名称");
            dgvWorkOrders.Columns.Add("colProductName", "产品名称");
            dgvWorkOrders.Columns.Add("colStatus", "状态");
            dgvWorkOrders.Columns.Add("colCreateDate", "创建日期");

            // 绑定单元格点击事件
            dgvWorkOrders.CellClick += DgvWorkOrders_CellClick;
        }

        private void DgvWorkOrders_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 0) // 复选框列
            {
                // 清除其他行的选择
                for (int i = 0; i < dgvWorkOrders.Rows.Count; i++)
                {
                    if (i != e.RowIndex)
                    {
                        dgvWorkOrders.Rows[i].Cells[0].Value = false;
                    }
                }

                // 设置当前行选中
                dgvWorkOrders.Rows[e.RowIndex].Cells[0].Value = true;

                // 获取选中的工单信息
                if (e.RowIndex < _workOrderData.Rows.Count)
                {
                    var row = _workOrderData.Rows[e.RowIndex];
                    _selectedWorkOrderName = row["WorkOrderName"]?.ToString() ?? "";
                    _selectedWorkOrderNumber = row["WorkOrderNumber"]?.ToString() ?? "";
                }
            }
        }

        private async void LoadWorkOrderData()
        {
            try
            {
                // 这里应该调用实际的API获取工单数据
                // 暂时使用模拟数据
                _workOrderData = CreateMockData();
                BindDataToGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载工单数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private DataTable CreateMockData()
        {
            var dt = new DataTable();
            dt.Columns.Add("WorkOrderNumber", typeof(string));
            dt.Columns.Add("WorkOrderName", typeof(string));
            dt.Columns.Add("ProductName", typeof(string));
            dt.Columns.Add("Status", typeof(string));
            dt.Columns.Add("CreateDate", typeof(DateTime));

            // 添加模拟数据
            dt.Rows.Add("WO001", "工单A", "产品A", "进行中", DateTime.Now.AddDays(-5));
            dt.Rows.Add("WO002", "工单B", "产品B", "已完成", DateTime.Now.AddDays(-10));
            dt.Rows.Add("WO003", "工单C", "产品C", "未开始", DateTime.Now.AddDays(-2));
            dt.Rows.Add("WO004", "工单D", "产品D", "进行中", DateTime.Now.AddDays(-7));
            dt.Rows.Add("WO005", "工单E", "产品E", "已完成", DateTime.Now.AddDays(-15));

            return dt;
        }

        private void BindDataToGrid()
        {
            dgvWorkOrders.Rows.Clear();
            foreach (DataRow row in _workOrderData.Rows)
            {
                int rowIndex = dgvWorkOrders.Rows.Add();
                dgvWorkOrders.Rows[rowIndex].Cells[1].Value = row["WorkOrderNumber"];
                dgvWorkOrders.Rows[rowIndex].Cells[2].Value = row["WorkOrderName"];
                dgvWorkOrders.Rows[rowIndex].Cells[3].Value = row["ProductName"];
                dgvWorkOrders.Rows[rowIndex].Cells[4].Value = row["Status"];
                dgvWorkOrders.Rows[rowIndex].Cells[5].Value = row["CreateDate"];
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            // 实现搜索功能
            string searchText = txtSearch.Text.Trim();
            if (!string.IsNullOrEmpty(searchText))
            {
                var filteredRows = _workOrderData.AsEnumerable()
                    .Where(row => row.Field<string>("WorkOrderNumber").Contains(searchText) ||
                                 row.Field<string>("WorkOrderName").Contains(searchText) ||
                                 row.Field<string>("ProductName").Contains(searchText))
                    .ToArray();

                var filteredTable = _workOrderData.Clone();
                foreach (var row in filteredRows)
                {
                    filteredTable.ImportRow(row);
                }

                _workOrderData = filteredTable;
                BindDataToGrid();
            }
            else
            {
                LoadWorkOrderData();
            }
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_selectedWorkOrderName) || string.IsNullOrEmpty(_selectedWorkOrderNumber))
            {
                MessageBox.Show("请选择一个工单", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13) // Enter键
            {
                btnSearch_Click(sender, e);
            }
        }
    }
}
